﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace T_Foundation.API.Extensios
{
    public static class  ServiceCollectionExtensions
    {
        /// <summary>
        /// 注入仓储
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            //services.AddScoped(typeof(IRepository<>), typeof(BaseRepository<>));
            //services.AddScoped<IPurchaseRepository, PurchaseRepository>();
            //services.AddScoped<IRequisitionRepository, RequisitionRepository>();
            //services.AddScoped<IWarehousingRepository, WarehousingRepository>();
            //services.AddScoped<IStatisticsRepository, StatisticsRepository>();

            return services;
        }

        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>

        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                var secreByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接受者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secreByte)
                };
            });
        }
    }
}
